package com.xrit.sunnyday.security;

import com.alibaba.dubbo.config.annotation.Reference;
import com.xrit.sunnyday.pojo.Permission;
import com.xrit.sunnyday.pojo.Role;
import com.xrit.sunnyday.pojo.User;
import com.xrit.sunnyday.service.UserService;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;

@Component
public class SpringSecurityUserService implements UserDetailsService {

    @Reference
    private UserService userService;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        //根据登陆用户名称查询用户权限信息
        User user = userService.findByUsername(username);
//        当用户权限不为空时，就遍历权限和用户角色的集合
        if (null!=user){
//            获取用户名和密码
            String password = user.getPassword();
//            存放所有权限的集合
         List<GrantedAuthority> authorities = new ArrayList<>();
            SimpleGrantedAuthority sga=null;
//            获取所有用户的角色
            Set<Role> roles = user.getRoles();
//             当角色不为空时，遍历给用户授予角色
            if (null != roles) {
//                遍历角色
                for (Role role : roles) {
//                给用户授予角色
                    sga = new SimpleGrantedAuthority(role.getKeyword());
                    authorities.add(sga);
//                    获取角色下所有的权限
                    Set<Permission> permissions = role.getPermissions();
//                    当权限不为空时，给角色授予权限
                    if (null != permissions) {
//                        遍历权限
                        for (Permission permission : permissions) {
//                            给角色授予权限
                            sga = new SimpleGrantedAuthority(permission.getKeyword());
                            authorities.add(sga);
                        }
                    }
                }
            }
//            把用户的权限和角色给返回
            return new org.springframework.security.core.userdetails.User(username,password,authorities);
        }
//        返回null，限制访问
        return null;
    }
}
